package com.oppo.result;


import lombok.Data;

/**
 * 全局统一返回结果类
 *
 * @author makejava
 * @since 2022-01-28 16:23:03
 */

@Data
@SuppressWarnings("unused")
public class BusinessResult<T> {

    private Integer code;

    private String message;

    private T data;

    public BusinessResult() {
    }


    // 返回数据
    protected static <T> BusinessResult<T> build(T data) {
        BusinessResult<T> result = new BusinessResult<>();
        if (data != null) {
            result.setData(data);
        }
        return result;
    }


    public static <T> BusinessResult<T> build(T body, ResultCodeEnum resultCodeEnum) {
        BusinessResult<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }


    public static <T> BusinessResult<T> success() {
        return BusinessResult.success(null);
    }


    /**
     * 操作成功
     *
     * @param data 数据
     * @return BusinessResult
     */
    public static <T> BusinessResult<T> success(T data) {
        BusinessResult<T> result = build(data);
        return build(data, ResultCodeEnum.SUCCESS);
    }


    public static <T> BusinessResult<T> fail() {
        return BusinessResult.fail(null);
    }


    /**
     * 操作失败
     *
     * @param data 数据
     * @param <T>  泛型
     * @return BusinessResult
     */
    public static <T> BusinessResult<T> fail(T data) {
        BusinessResult<T> result = build(data);
        return build(data, ResultCodeEnum.FAIL);
    }


    public BusinessResult<T> message(String msg) {
        this.setMessage(msg);
        return this;
    }


    public BusinessResult<T> code(Integer code) {
        this.setCode(code);
        return this;
    }


    public boolean isOk() {
        return this.getCode().intValue() == ResultCodeEnum.SUCCESS.getCode().intValue();
    }


}

